<?php

/**
 * This class manages all database queries (or other operations)
 *  concerning events.
 */
class Model_Event extends Model_Base
{

    // Accepted Errors
    public static $EXCEEDS_MAX_TOTAL_PARALLEL_CARESITS = "Maximale Anzahl gleichzeitiger Betreuungsplätze überschritten";
    public static $EXCEEDS_MAX_TOTAL_PARALLEL_CARESITS_FOR_CHILDREN_UNDER_ONE = "Maximale Anzahl gleichzeitiger Betreuungsplätze für Kinder unter 1 Jahr überschritten";
    public static $EXCEEDS_MAX_CAREDAYS_FOR_CHILDREN_UNDER_AGE_ONE = "Maximale Anzahl an Betreuungstage pro Woche für Kinder unter 1. Jahr überschritten";
    public static $EXCEEDS_MAX_CAREDAYS_FOR_CHILDREN_OVER_AGE_ONE = "Maximale Anzahl an Betreuungstage pro Woche für Kinder über 1. Jahr überschritten";
    public static $EXCEEDS_MAX_CARE_HOURS_FOR_CHILD_AND_WEEK = "Maximale Anzahl der Stunden pro Woche überschritten";
    // Accepted status codes
    public static $STATUS_ACCEPTED = "Angenommen";
    public static $STATUS_DECLINED = "Abgelehnt";

    /**
     *
     * @var type Zend_Log
     */
    private static $logger = NULL;

    /**
     * Database table name
     *
     * @var string
     */
    protected $name = 'event';
    private $modelStatusflag;

    function __construct()
    {
	parent::__construct();
	$this->modelStatusflag = new Model_Statusflag;
	$this->initLogging();
    }

    private function initLogging()
    {
	if (self::$logger === NULL)
	{
	    try
	    {
		self::$logger = new Zend_Log();
		$thisClass = get_class($this);
		$logPath = APPLICATION_PATH . "/log/$thisClass.log";
		self::$logger->addWriter(new Zend_Log_Writer_Stream($logPath));
		self::$logger->log("Logger initialized for $thisClass", Zend_Log::INFO);
	    } catch (Exception $e)
	    {
		self::$logger->addWriter(new Fkb_Log_NullLogger());
	    }
	}
    }

    public function setModelStatusflag(Model_Statusflag $modelStatusflag)
    {
	$this->modelStatusflag = $modelStatusflag;
    }

    public function getModelStatusflag()
    {
	return $this->modelStatusflag;
    }

    /**
     * Lists all events, ordered by date.
     * 
     * @deprecated
     * @return array an array of (associative) arrays
     */
    public function listAll($category = false)
    {
	if ($category === false)
	{
	    $category = array('Fester Termin', 'Eingewöhnungstermin', 'Einzeltermin', 'Gesprächstermin', 'Konferenz', 'Feste/Veranstaltungen', 'Sonstiges');
	}
	$select = $this->db->select()
		->from($this->name)
		->where("event_type IN (?)", $category)
		->order('date_from ASC');
	echo $select;

	return $this->db->fetchAll($select);
    }

    public function listEventsBetween($from, $until, $category = false, $denied = false)
    {
	if (!is_object($from) || get_class($from) != "Zend_Date")
	    $from = new Zend_Date($from, Zend_Date::ISO_8601);
	if (!is_object($until) || get_class($until) != "Zend_Date")
	    $until = new Zend_Date($until, Zend_Date::ISO_8601);
	if ($category === false)
	{
	    $category = array('Fester Termin', 'Eingewöhnungstermin', 'Einzeltermin', 'Gesprächstermin', 'Konferenz', 'Feste/Veranstaltungen', 'Sonstiges');
	}
	if ($denied == 'Abgelehnt')
	{
	    $addWhere = "event_status='Abgelehnt'";
	} elseif ($denied == 'both')
	{
	    $addWhere = "1=1";
	} else
	{
	    $addWhere = "event_status='Angenommen' or event_status IS NULL";
	}
	$select = $this->db->select()
		->from($this->name)
		->where('date_from > ?', $from->toString('YYYY-MM-dd HH:m:ss'))
		->where('date_from < ?', $until->toString('YYYY-MM-dd HH:m:ss'))
		->where('event_type IN (?)', $category)
		->where($addWhere)
		->order('date_from ASC');
	return $this->db->fetchAll($select);
    }

    public function listWeek($year = false, $week = false, $category = false, $denied = false)
    {
	$date = new Zend_Date();
	if ($year === false)
	    $year = $date->get(Zend_Date::YEAR);
	if ($week === false)
	    $week = $date->get(Zend_Date::WEEK);
	$date->setHour(0);
	$date->setMinute(0);
	$date->setSecond(0);
	$date->setYear($year);
	$date->setWeek($week);
	$date->setWeekday(1);
	return $this->listEventsBetween($date->get(), $date->addDay(7)->get(), $category, $denied);
    }

    /**
     * Persists a new event to the database.
     * 
     * @param array $event the events data
     */
    public function create(array $event, $forceSingleEvent = false)
    {
	if ($event['frequence'] == 'WEEKLY' && $forceSingleEvent === false)
	{

	    $eventDateFrom = new Zend_Date($event['date_from']);
	    $eventDateTo = new Zend_Date($event['date_to']);
	    $eventLastDate = new Zend_Date($event['last_date']);
	    $modelSeries = new Model_Series;
	    $event['idevent_series'] = $modelSeries->create();
	    $dates = $this->listDatesBetween($eventDateFrom, $eventLastDate);

	    foreach ($dates as $date) /* @var $date Zend_Date */
	    {
		$eventToAddDateFrom = clone $date;
		$eventToAddDateTo = clone $date;

		$eventToAddDateFrom->setTime($eventDateFrom->getTime());
		$eventToAddDateTo->setTime($eventDateTo->getTime());

		$event['date_from'] = $eventToAddDateFrom->toString();
		$event['date_to'] = $eventToAddDateTo->toString();
		unset($event['child_id'], $event['frequence'], $event['last_date']);
		$this->create($event, true);
	    }
	} else
	{
	    unset($event['child_id'], $event['frequence'], $event['last_date']);
	    $date_from = new Zend_Date($event['date_from']);
	    $event['date_from'] = $date_from->toString(Zend_Date::ISO_8601);
	    $date_to = new Zend_Date($event['date_to']);
	    $event['date_to'] = $date_to->toString(Zend_Date::ISO_8601);
	    $this->db->insert($this->name, $event);
	    return $this->lastCreatedId();
	}
    }

    /**
     * Updates a event_series.
     * 
     * @param array $event the events data
     */
    public function updateSeries(array $event)
    {
//TODO: handle different Formfields
	unset($event['child_id'], $event['frequence'], $event['last_date']);

	$date_from = new Zend_Date($event['date_from']);
	$event['date_from'] = $date_from->toString(Zend_Date::ISO_8601);
	$date_to = new Zend_Date($event['date_to']);
	$event['date_to'] = $date_to->toString(Zend_Date::ISO_8601);
// @TODO: handle all events here
//var_Dump($event);
	$select = $this->db->select()
		->from($this->name)
		->where('date_from > ?', $event['date_from'])
		->where('idevent_series = ?', $event['series_id'])
		->orWhere('id = ?', $event['id'])
		->order('id ASC');
//print($select->__toString());
//exit();

	$allEvents = $this->db->fetchAll($select);
	unset($event['series_id'], $event['id']);
	$date_from->subWeek(1);
	$date_to->subWeek(1);
	foreach ($allEvents as $singleEvent)
	{
	    $date_from->addWeek(1);
	    $date_to->addWeek(1);
	    $event['date_from'] = $date_from->toString(Zend_Date::ISO_8601);
	    $event['date_to'] = $date_to->toString(Zend_Date::ISO_8601);
	    $where = $this->db->quoteInto('id = ?', $singleEvent['id']);
	    $this->db->update($this->name, $event, $where);
	}
    }

    /**
     * Updates an events data.
     * 
     * @param array $event the events data
     */
    public function update(array $event)
    {
//TODO: handle different Formfields
	unset($event['child_id'], $event['frequence'], $event['last_date']);

	$date_from = new Zend_Date($event['date_from']);
	$event['date_from'] = $date_from->toString(Zend_Date::ISO_8601);
	$date_to = new Zend_Date($event['date_to']);
	$event['date_to'] = $date_to->toString(Zend_Date::ISO_8601);

	$where = $this->db->quoteInto('id = ?', $event['id']);
	$this->db->update($this->name, $event, $where);
    }

    /**
     * Get an events data. The event is identified by its id.
     * 
     * @param type $id the events id
     * @return array the events data, or FALSE if not found
     */
    public function find($id)
    {
	$select = $this->db->select()
		->from($this->name)
		->where('id = ?', $id);
	return $this->db->fetchRow($select);
    }

    /**
     * Removes an event from the database identified by its id.
     * 
     * @param type $id the events id
     */
    public function delete($id)
    {
//Abgesagter Termin oder wirklich löschen?
	$event = $this->find($id);
	if ($event['event_type'] == 'Fester Termin' || $event['event_type'] == 'Einzeltermin' || $event['event_type'] == 'Eingewöhnungstermin' || $event['event_type'] == 'Abgesagter Termin')
	{
	    $where = $this->db->quoteInto('id = ?', $id);
	    $this->db->update($this->name, array('event_type' => 'Abgesagter Termin'), $where);
	} else
	{
	    $where = $this->db->quoteInto('id = ?', $id);
	    $this->db->delete($this->name, $where);
	}
    }

    public function deleteSeries($id)
    {
	$event = $this->find($id);
	$select = $this->db->select()
		->from($this->name)
		->where('date_from >= ?', $event['date_from'])
		->where('idevent_series = ?', $event['idevent_series'])
		->order('id ASC');
	$allEvents = $this->db->fetchAll($select);
	foreach ($allEvents as $singleEvent)
	{
	    $this->delete($singleEvent['id']);
	}
    }

    /**
     * Removes all events from the database
     * 
     * @param type $id the events id
     */
    public function deleteAll()
    {
	$this->db->delete($this->name);
    }

    public function lastCreatedId()
    {
	return $this->db->lastInsertId($this->name);
    }

    public function lastCreated()
    {
	return $this->find($this->lastCreatedId());
    }

    /**
     * Lists event dates for a given timespan 
     * @param Zend_Date $startDate Begin of the timespan
     * @param Zend_Date $endDate End of the timespan
     * @return array(Zend_Date) List of dates
     */
    public function listDatesBetween($startDate, $endDate)
    {
	if (get_class($startDate) != "Zend_Date" or get_class($startDate) != "Zend_Date")
	{
	    throw new InvalidArgumentException("Arguments must be of type Zend_Date");
	} else if (!$startDate->isEarlier($endDate))
	{
	    throw new InvalidArgumentException("Startdate must not be earlier than enddate");
	}
//fixes the isEarlierProblem
	$endDate->addDay(1);
	$dates = array();
	$currentDate = clone $startDate;

	while ($currentDate->isEarlier($endDate))
	{
	    array_push($dates, clone $currentDate);
	    $currentDate = $currentDate->addWeek(1);
	}

	return $dates;
    }

    private function log_method($method)
    {
	self::$logger->log("Called method $method", Zend_Log::DEBUG);
    }

    /**
     * Checks weather space is available in the given timerange
     * @param Zend_Date $startDate
     * @param Zend_Date $endDate
     * @return boolean Yes or not
     */
    public function exceedsMaxTotalParallelCaresits($event)
    {
	$this->log_method(__METHOD__);
	$validEventTypes = array(
	    Application_Form_Event::$REQUEST_TYPES_Childevents['Fester Termin'],
	    Application_Form_Event::$REQUEST_TYPES_Childevents['Einzeltermin'],
	);

	if (!in_array($event['event_type'], $validEventTypes))
	{
	    return false;
	}

	$startDate = ($event['date_from'] instanceof Zend_Date ) ? $event['date_from'] : new Zend_Date($event['date_from']);
	$endDate = ($event['date_to'] instanceof Zend_Date ) ? $event['date_to'] : new Zend_Date($event['date_to']);

	$startDateAsString = $startDate->toString(Zend_Date::ISO_8601);
	$endDateAsString = $endDate->toString(Zend_Date::ISO_8601);

	$maxCareSits = $this->modelStatusflag->getMaxParallelCareSitsTotal();

	$select = $this->db->select()
		->from($this->name, array('count' => 'COUNT(*)'))
		->where("(NOT (date_from >= '$endDateAsString' OR date_to <= '$startDateAsString'))")
		->where("event_type IN (?)", $validEventTypes)
		->where('(event_status = ?) or (event_status is null)', self::$STATUS_ACCEPTED);

	$this->log_method($select);

	$res = $this->db->fetchAll($select);
	return $res[0]['count'] >= $maxCareSits;
    }

    /**
     * 
     * @param Zend_Date $eventPartStart
     * @param Zend_Date $eventPartEnd
     * @param array $events
     */
    public function concurrentEvents($eventPartStart, $eventPartEnd, $events){
	$concurrentEvents = 0;
	foreach ($events as $event){
	    $eventDateFrom = new Zend_Date($event['date_from']);
	    $eventDateTo = new Zend_Date($event['date_to']);
	    if  (!($eventPartStart->compare($eventDateTo)!= -1 || $eventPartEnd->compare($eventDateFrom) != 1)){
		$concurrentEvents++;
	    }
	}
	return $concurrentEvents;
    }


    /**
     * 
     * @param array $event
     * @param array $events
     * @return Integer
     */
    public function maxConcurrentEvents($event, $events)
    {
	$eventParts = $this->extractEventParts($event);
	$maxConcurrentEvents = 0;
		for ($i=0 ;$i<count($eventParts) - 1 ;$i++){
	    $concurentEvents = $this->concurrentEvents($eventParts[$i], $eventParts[$i+1], $events);
	    if ($concurentEvents > $maxConcurrentEvents){
		$maxConcurrentEvents = $concurentEvents;
	    }
	}
	return $maxConcurrentEvents;
    }

    public function extractEventParts($event)
    {
	$eventStart = new Zend_Date($event['date_from']);
	$eventEnd = new Zend_Date($event['date_to']);

	$eventParts = array(clone $eventStart);
	$currentEvent = clone $eventStart;

	do
	{
	    $currentEvent->addMinute(15);
	    array_push($eventParts, clone $currentEvent);
	} while ($currentEvent->isEarlier($eventEnd));
	
	return $eventParts;
    }

    public function exceedsMaxTotalParallelCaresitsForChildrenUnderOne($event)
    {
	$this->log_method(__METHOD__);
	$validEventTypes = array(
	    Application_Form_Event::$REQUEST_TYPES_Childevents['Fester Termin'],
	    Application_Form_Event::$REQUEST_TYPES_Childevents['Einzeltermin'],
	);

	if (!in_array($event['event_type'], $validEventTypes))
	{
	    return false;
	}

	$startDate = ($event['date_from'] instanceof Zend_Date ) ? $event['date_from'] : new Zend_Date($event['date_from']);
	$endDate = ($event['date_to'] instanceof Zend_Date ) ? $event['date_to'] : new Zend_Date($event['date_to']);

	$startDateAsString = $startDate->toString(Zend_Date::ISO_8601);
	$endDateAsString = $endDate->toString(Zend_Date::ISO_8601);

	$maxParallelCareSitsForChildrenUnderOne = $this->modelStatusflag->getMaxParallelCareSitsForChildrenUnderOne();

	$select = $this->db->select()
		->from(array('e' => $this->name), array('count' => 'COUNT(*)'))
		->distinct()
		->join(array('elp' => 'event_link_person'), 'e.id=elp.idevent', array())
		->join(array('p' => 'person'), 'p.id=elp.idperson', array())
		->where("(NOT (date_from >= '$endDateAsString' OR date_to <= '$startDateAsString'))")
		->where("e.event_type IN (?)", $validEventTypes)
		->where('(event_status = ?) or (event_status is null)', self::$STATUS_ACCEPTED)
		->where("DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(p.birthday, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(p.birthday, '00-%m-%d')) < 1");

	$res = $this->db->fetchAll($select);
	return $res[0]['count'] >= $maxParallelCareSitsForChildrenUnderOne;
    }

    public function exceedsMaxCaredaysForChildrenUnderAgeOne($event, $child)
    {
	$this->log_method(__METHOD__);
	return $this->exeedsMaxCaredaysForChildrenUsingAge(
			$event, $child, $this->modelStatusflag->getMaxWeeklyCareSitsForChildrenUnderOne(), '< 1');
    }

    public function exceedsMaxCaredaysForChildrenOverAgeOne($event, $child)
    {
	$this->log_method(__METHOD__);
	return $this->exeedsMaxCaredaysForChildrenUsingAge(
			$event, $child, $this->modelStatusflag->getMaxWeeklyCareSitsForChildrenOverOne(), '>= 1');
    }

    public function exceedsMaxCareHoursForChildAndWeek($child, $event)
    {
	$this->log_method(__METHOD__);

	$validEventTypes = array(
	    Application_Form_Event::$REQUEST_TYPES_Childevents['Fester Termin'],
	);

	if (!in_array($event['event_type'], $validEventTypes))
	{
	    return false;
	}

	return $this->careHoursForChildAndWeek($child, $event, true) > $this->modelStatusflag->getMaxCareHoursPerWeek();
    }

    private function exeedsMaxCaredaysForChildrenUsingAge($event, $child, $maxCaredays, $age_clause)
    {
	$this->log_method(__METHOD__);
	$validEventTypes = array(
	    Application_Form_Event::$REQUEST_TYPES_Childevents['Fester Termin'],
	);

	if (!in_array($event['event_type'], $validEventTypes))
	{
	    return false;
	}

	$startDate = ($event['date_from'] instanceof Zend_Date ) ? $event['date_from'] : new Zend_Date($event['date_from']);
	$endDate = clone $startDate;

	$this->modifyToWeekRange($startDate, $endDate);

	$startDateAsString = $startDate->toString(Zend_Date::ISO_8601);
	$endDateAsString = $endDate->toString(Zend_Date::ISO_8601);

	$select = $this->db->select()
		->from(array('e' => $this->name), array('count' => 'COUNT(*)'))
		->join(array('elp' => 'event_link_person'), 'e.id=elp.idevent', array())
		->join(array('p' => 'person'), 'p.id=elp.idperson', array())
		->where("e.date_from >= '$startDateAsString'")
		->where("e.date_to <= '$endDateAsString'")
		->where('p.id = ?', $child['id'])
		->where('e.event_status = ?', self::$STATUS_ACCEPTED)
		->where("e.event_type IN (?)", $validEventTypes)
		->where("DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(p.birthday, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(p.birthday, '00-%m-%d')) $age_clause");

	$res = $this->db->fetchAll($select);
	return $res[0]['count'] >= $maxCaredays ? true : false;
    }

    private function modifyToWeekRange($startDate, $endDate)
    {
	$startDate->set(1, Zend_Date::WEEKDAY_DIGIT);
	$startDate->setTime('00:00:00', 'HH:m:ss');
	$endDate->set(5, Zend_Date::WEEKDAY_DIGIT);
	$endDate->setTime('23:59:59', 'HH:m:ss');
    }

    public function careHoursForChildAndWeek($child, $event, $includeEvent = false)
    {
	$this->log_method(__METHOD__);
	$childId = $child['id'];
	if ($childId === null)
	{
	    throw new InvalidArgumentException("Child id not set");
	}

	$eventDateFrom = ($event['date_from'] instanceof Zend_Date) ? $event['date_from'] : new Zend_Date($event['date_from']);
	$eventDateTo = ($event['date_to'] instanceof Zend_Date) ? $event['date_to'] : new Zend_Date($event['date_to']);

	self::$logger->log("Event: " . $eventDateFrom->toString(Zend_Date::ISO_8601) . " -> " . $eventDateTo->toString(Zend_Date::ISO_8601), Zend_Log::INFO);

	$rangeStart = clone $eventDateFrom;
	$rangeEnd = clone $rangeStart;
	$this->modifyToWeekRange($rangeStart, $rangeEnd);

	self::$logger->log("Modified Range to: "
		. $rangeStart->toString(Zend_Date::ISO_8601)
		. " -> "
		. $rangeEnd->toString(Zend_Date::ISO_8601)
		, Zend_Log::INFO);

	$rangeStartAsString = $rangeStart->toString(Zend_Date::ISO_8601);
	$rangeEndAsString = $rangeEnd->toString(Zend_Date::ISO_8601);

	$select = $this->db->select()
		->distinct()
		->from(array('e' => $this->name))
		->join(array('elp' => 'event_link_person'), 'e.id=elp.idevent', array())
		->join(array('p' => 'person'), 'p.id=elp.idperson', array())
		->where('e.event_status = ?', self::$STATUS_ACCEPTED)
		->where('e.event_type = ?', $event['event_type'])
		->where("(e.date_from >= '$rangeStartAsString' and e.date_from < '$rangeEndAsString') OR (e.date_to > '$rangeStartAsString' and e.date_to <= '$rangeEndAsString')")
		->where('p.id = ?', $childId);

	$res = $this->db->fetchAll($select);

	self::$logger->log("Found " . count($res) . " events", Zend_Log::INFO);

	$totalTimeAsTimestamp = 0;

	foreach ($res as $event)
	{
	    $dateFrom = new Zend_Date($event['date_from']);
	    $dateTo = new Zend_Date($event['date_to']);
	    $totalTimeAsTimestamp += $dateTo->sub($dateFrom)->getTimestamp();
	}

	if ($includeEvent)
	{
	    $totalTimeAsTimestamp += $eventDateTo->sub($eventDateFrom)->getTimestamp();
	}

	$totalHours = $totalTimeAsTimestamp / 60 / 60;
	self::$logger->log("Total hours: $totalHours", Zend_Log::INFO);
	return $totalHours;
    }

    private function booleanToString($boolean)
    {
	return $boolean ? "true" : "false";
    }

    public function getAcceptedStatus($child, $event, &$errors = null)
    {
	if ($errors == null)
	{
	    $errors = array();
	}
	$this->log_method(__METHOD__);
	$modelChild = new Model_Child();
	$age = $modelChild->getAgeInYearsNew($child['birthday']);

	$accepted = true;

	$exceedsMaxCareHoursForChildAndWeek = $this->exceedsMaxCareHoursForChildAndWeek($child, $event);
	if ($exceedsMaxCareHoursForChildAndWeek)
	{
	    self::$logger->log(self::$EXCEEDS_MAX_CARE_HOURS_FOR_CHILD_AND_WEEK, Zend_Log::INFO);
	    array_push($errors, self::$EXCEEDS_MAX_CARE_HOURS_FOR_CHILD_AND_WEEK);
	}
	$accepted &=!$exceedsMaxCareHoursForChildAndWeek;


	$exceedsMaxTotalParallelCaresits = $this->exceedsMaxTotalParallelCaresits($event);
	if ($exceedsMaxTotalParallelCaresits)
	{
	    self::$logger->log(self::$EXCEEDS_MAX_TOTAL_PARALLEL_CARESITS, Zend_Log::INFO);
	    array_push($errors, self::$EXCEEDS_MAX_TOTAL_PARALLEL_CARESITS);
	}
	$accepted &=!$exceedsMaxTotalParallelCaresits;

	if ($age < 1)
	{
	    $exceedsMaxCaredaysForChildrenUnderAgeOne = $this->exceedsMaxCaredaysForChildrenUnderAgeOne($event, $child);
	    if ($exceedsMaxCaredaysForChildrenUnderAgeOne)
	    {
		self::$logger->log(self::$EXCEEDS_MAX_CAREDAYS_FOR_CHILDREN_UNDER_AGE_ONE, Zend_Log::INFO);
		array_push($errors, self::$EXCEEDS_MAX_CAREDAYS_FOR_CHILDREN_UNDER_AGE_ONE);
	    }
	    $accepted &=!$exceedsMaxCaredaysForChildrenUnderAgeOne;


	    $exceedsMaxTotalParallelCaresitsForChildrenUnderOne = $this->exceedsMaxTotalParallelCaresitsForChildrenUnderOne($event);
	    if ($exceedsMaxTotalParallelCaresitsForChildrenUnderOne)
	    {
		self::$logger->log(self::$EXCEEDS_MAX_TOTAL_PARALLEL_CARESITS_FOR_CHILDREN_UNDER_ONE, Zend_Log::INFO);
		array_push($errors, self::$EXCEEDS_MAX_TOTAL_PARALLEL_CARESITS_FOR_CHILDREN_UNDER_ONE);
	    }
	    $accepted &=!$exceedsMaxTotalParallelCaresitsForChildrenUnderOne;
	} else
	{
	    $exceedsMaxCaredaysForChildrenOverAgeOne = $this->exceedsMaxCaredaysForChildrenOverAgeOne($event, $child);
	    if ($exceedsMaxCaredaysForChildrenOverAgeOne)
	    {
		self::$logger->log(self::$EXCEEDS_MAX_CAREDAYS_FOR_CHILDREN_OVER_AGE_ONE, Zend_Log::INFO);
		array_push($errors, self::$EXCEEDS_MAX_CAREDAYS_FOR_CHILDREN_OVER_AGE_ONE);
	    }
	    $accepted &=!$exceedsMaxCaredaysForChildrenOverAgeOne;
	}

	return ($accepted == true) ? self::$STATUS_ACCEPTED : self::$STATUS_DECLINED;
    }

    public function areEventsBetweenByDate($from, $until)
    {
//returns true if events exist
	if (!is_object($from) || get_class($from) != "Zend_Date")
	    $from = new Zend_Date($from);
	if (!is_object($until) || get_class($until) != "Zend_Date")
	    $until = new Zend_Date($until);

	$select = $this->db->select()
		->from('event')
		->where('event_type != ?', "Abgesagter Termin")
		->where('event_status = ?', "Abgelehnt")
		->where('date_from > ?', $until->toString('YYYY-MM-dd HH:m:ss') and
			'date_to > ?', $from->toString('YYYY-MM-dd HH:m:ss'))
		->orWhere('date_from = ?', $from->toString('YYYY-MM-dd HH:m:ss') and
		'date_to = ?', $until->toString('YYYY-MM-dd HH:m:ss'));

	$rows = $this->db->fetchAll($select);
	return (!empty($rows));
    }

    public function areEventsBetween($id)
    {
//returns false wenn der event_type des gelöschten Termins kein Betreuungstermin ist
//oder wenn zu dem gelöschten Zeitpunkt keine Alternativtermine gefunden wurden
//returns true wenn Abgelehnte Termine in dem Zeitraum vorhanden sind
	$event = $this->find($id);
	if ($event['event_type'] = 'Einzeltermin' || $event['event_type'] = 'Fester Termin' || $event['event_type'] = 'Eingewöhnungstermin')
	    return $this->areEventsBetweenByDate($event['date_from'], $event['date_to']);
	else
	    return false;
    }

}